// globalRecorder.js
import Recorder from 'recorder-core';
// 引入 WAV 录音引擎和波形绘制扩展（根据项目需要调整引入路径）
import 'recorder-core/src/engine/wav.js';
import 'recorder-core/src/extensions/waveview.js';
/** 引入RecordApp **/
import RecordApp from 'recorder-core/src/app-support/app.js'
// #ifdef MP-WEIXIN
//可选引入微信小程序支持文件
import 'recorder-core/src/app-support/app-miniProgram-wx-support.js'
// #endif
// #ifdef H5 || MP-WEIXIN
//按需引入需要的录音格式编码器，用不到的不需要引入，减少程序体积；H5、renderjs中可以把编码器放到static文件夹里面用动态创建script来引入，免得这些文件太大
import 'recorder-core/src/engine/mp3.js'
import 'recorder-core/src/engine/mp3-engine.js'
import 'recorder-core/src/engine/wav.js'

// #endif
import {
	useRecordingStore
} from '@/store/useRecordingStore.js';
import {
	createPinia
} from 'pinia';
import {
	onActivated,
	nextTick
} from 'vue';

// 全局变量
let recorder = null;
let recordingStatus = false;
let waveView = null; // 用于存储波形绘制实例
let recpowert = null;
let aBufData = null;
let powerLevelData = null;
let sampleRateData = null;
const pinia = createPinia(); // 创建 Pinia 实例
let recordingStore = null;
let durationData = 0; // 用于存储录音时长
let mimeData = null; // 用于存储 mime 类型数据

export function getRecordingStore() {
	if (!recordingStore) {
		recordingStore = useRecordingStore(pinia); // 确保 pinia 被传入
	}
	return recordingStore
}

const store = getRecordingStore()
if (store) {
	console.log('录音状态:', store.isRecording)
}

export function recReq() {
	RecordApp.UniNativeUtsPlugin = {
		nativePlugin: true
	}; // 恢复原生插件配置值
	console.log('正在请求录音权限...');
	RecordApp.RequestPermission(() => {
		console.log('已获得录音权限，可以开始录音了');
	}, (msg, isUserNotAllow) => {
		if (isUserNotAllow) { //用户拒绝了录音权限
			//这里你应当编写代码检查wx.getSetting中的scope.record录音权限，引导用户进行授权
			wx.showModal({
				title: "需要录音权限",
				content: "请到设置中允许小程序访问麦克风",
				confirmText: "打开设置",
				success: (res) => {
					if (res.confirm) wx.openSetting();
				}
			});
		}
		console.log('请求录音权限失败');
	});
}

export function drawCanvas(vue3This, callback) {
	RecordApp.UniFindCanvas(vue3This, [".recwave-WaveView"], `
	   this.waveView = Recorder.WaveView({
		 compatibleCanvas: canvas1,
		 width: 300,
		 height: 100
	   });
	 `, (canvas1) => {
		vue3This.waveView = Recorder.WaveView({
			compatibleCanvas: canvas1,
			width: 300,
			height: 100,
		});
		waveView = vue3This.waveView
		if (typeof callback === 'function') {
			callback(vue3This.waveView);
		}
		console.log('我再看看你：',waveView);
	});
}

/**
 * 开始录音，并在指定的 canvas 上显示波形
 * @param {Object} options - 配置项，例如 { sampleRate: 16000, bitRate: 16 }
 * @param {Function} onProcessCallback - 处理录音数据的回调函数
 * @param {HTMLCanvasElement} waveCanvasElement - 绘制波形的 canvas 元素（可选）
 */
export function startRecordingWithVisualization(vue3This, options = {}, onProcessCallback) {
	if (recordingStatus) return; // 如果已在录音，直接返回
	const {
		sampleRate = 16000, bitRate = 16
	} = options;

	// 启动录音
	RecordApp.Start({
		type: 'wav',
		sampleRate: sampleRate,
		bitRate: bitRate,
		onProcess: function(buffers, powerLevel, duration, sampleRate, newBufferIdx, asyncEnd) {
			recpowert = formatTime(duration, 1);
			aBufData = buffers;
			durationData = duration;
			powerLevelData = powerLevel
			sampleRateData = sampleRate
			mimeData = 'wav'; // 假设使用的是 wav 格式
			// console.log('你是什么东西啊：',vue3This.waveView);
			// 在小程序中直接在逻辑层绘制波形
			if (vue3This.waveView) {
				vue3This.waveView.input(buffers[buffers.length - 1], powerLevel, sampleRate);
				// console.log('12121212121212', vue3This.waveView);
			}
			// 调用用户自定义的处理回调（如果有）
			if (typeof onProcessCallback === 'function') {
				onProcessCallback(buffers, powerLevel, duration, sampleRate, newBufferIdx, asyncEnd);
			}
		}
	});
	// 记录录音状态
	recordingStatus = true;
	// store.startRecording(RecordApp.GetCurrentRecOrNull()); // 存储录音实例

	// 创建音频可视化图形绘制，H5、小程序在逻辑层绘制
	// RecordApp.UniFindCanvas(vue3This, [".recwave-WaveView"], `
	//    this.waveView = Recorder.WaveView({
	// 	 compatibleCanvas: canvas1,
	// 	 width: 300,
	// 	 height: 100
	//    });
	//  `, (canvas1) => {
	// 	console.log(888888888888888888888);
	// 	vue3This.waveView = Recorder.WaveView({
	// 		compatibleCanvas: canvas1,
	// 		width: 300,
	// 		height: 100
	// 	});
	// });
}

// 恢复波形绘制的具体逻辑
export function reconnectWaveView(vue3This, onProcessCallback) {
	const currentRec = RecordApp.GetCurrentRecOrNull();
	if (currentRec && currentRec.set) {
		// 重新设置 onProcess，确保数据绘制到正确的 canvas 上
		currentRec.set.onProcess = function(buffers, powerLevel, duration, sampleRate, newBufferIdx, asyncEnd) {

			// 记录时长及缓冲区数据
			recpowert = formatTime(duration, 1);
			aBufData = buffers;
			durationData = duration;
			powerLevelData = powerLevel
			sampleRateData = sampleRate
			mimeData = 'wav';
			// console.log('你是神恶魔东西：',buffers);
			// 触发 waveView 绘制
			if (vue3This.waveView) {
				// console.log('🌊 调用了 waveView.input()',vue3This.waveView);
				vue3This.waveView.input(buffers[buffers.length - 1], powerLevel, sampleRate);
			}

			// 调用用户自定义的处理回调（如果有）
			if (typeof onProcessCallback === 'function') {
				onProcessCallback(buffers, powerLevel, duration, sampleRate, newBufferIdx, asyncEnd);
			}

			console.log('✅ 波形恢复完成');
		};
	}
}

/**
 * 停止录音，同时清理波形绘制实例
 */
export function stopRecording(onProcessCallback) {
	if (recordingStatus) {
		RecordApp.Stop(async (aBuf, duration, mime) => {
			onProcessCallback(aBuf, duration, mime)
			// aBufData = aBuf
		})
		recordingStatus = false;
		store.stopRecording();
		// 清理 waveView 实例
		waveView = null;
	}
}

/**
 * 暂停录音
 */
export function pauseRecording(onProcessCallback) {
	if (recordingStatus && RecordApp.GetCurrentRecOrNull()) {
		RecordApp.Pause();
		onProcessCallback(aBufData, durationData, mimeData);
	}
}

/**
 * 继续录音
 */
export function resumeRecording() {
	console.log('进来继续');
	if (recordingStatus && RecordApp.GetCurrentRecOrNull()) {
		console.log('继续了吗？',RecordApp);
		RecordApp.Resume();
	}
}

/**
 * 取消录音
 */
export function cancelRecording() {
	if (recordingStatus) {
		RecordApp.Stop(); //清理资源，如果打开了录音没有关闭，这里将会进行关闭
		recordingStatus = false;
		waveView = null;
	}
}

/**
 * 获取当前录音实例
 */
export function getRecorder() {
	return recorder;
}

/**
 * 返回录音是否正在进行
 */
export function isRecording() {
	return recordingStatus;
}

/**
 * 返回当前的波形绘制实例（如果存在）
 */
export function getWaveView() {
	return waveView;
}

/**
 * 返回当前的录音文件
 */
export function getABufData() {
	return aBufData;
}

export function getPowerLevel() {
	return powerLevelData;
}

export function getSampleRate() {
	return sampleRateData;
}

/**
 * 返回录音时长样式
 */
export function formatTime(ms, showSS) {
	var ss = ms % 1000;
	ms = (ms - ss) / 1000;
	var s = ms % 60;
	ms = (ms - s) / 60;
	var m = ms % 60;
	ms = (ms - m) / 60;
	var h = ms,
		v = "";
	if (h > 0) v += (h < 10 ? "0" : "") + h + ":";
	v += (m < 10 ? "0" : "") + m + ":";
	v += (s < 10 ? "0" : "") + s;
	if (showSS) v += "." + ("00" + ss).substr(-3,2);
	return v;
}

/**
 * 返回录音时长
 */
export function getRecpowert() {
	return recpowert;
}